package cn.doctor.assistant.pad.ui;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.widget.Toast;

import net.tsz.afinal.http.AjaxCallBack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.api.UploadPictureAPI;
import cn.doctor.assistant.pad.base.BaseNetActivity;

/**
 * Created by jiaolf on 2016/4/14.
 */
public class UploadImageActivity extends BaseNetActivity{
    /**
     * 照相获取图片
     */
    File cameraFile = null;
    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_LOCAL = 19;

    private static final int REQUESTCODE_CUTTING = 2;

    // 是否为头像文件
    public boolean isIconFile;

    // 用来区分拍照的调用者.调用拍照以后,获取到照片的路径后可以区分是什么功能调用了.
    protected int mUploadTag = -1;

    // 从相机选择一个照片,传入参数tag, 用来区分调用者来源.
    public void selectPicFromCamera(int tag) {
        cameraFile = new File(Environment.getExternalStorageDirectory(), + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
        mUploadTag = tag;
    }

    /**
     * 从图库获取图片
     */
    public void selectPicFromLocal(int tag) {
        Intent intent = new Intent("android.intent.action.PICK", null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
        mUploadTag = tag;

    }

    /**
     * onActivityResult
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 清空消息
            if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                if (cameraFile != null && cameraFile.exists()) {
                    if (isIconFile) {
                        startPhotoZoom(Uri.fromFile(cameraFile));
                    } else {
                        sendPicture(cameraFile.getAbsolutePath());
                    }
                }
            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                Uri selectedImage = data.getData();
                if (selectedImage != null) {

                    if (isIconFile) {
                        startPhotoZoom(selectedImage);
                    } else {
                        sendPicByUri(selectedImage);
                    }
                }
            } else if (requestCode == REQUESTCODE_CUTTING) {
                if (data != null) {
                    setPicToView(data);
                }
            }
        }
    }

    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            File img = bitmapToPng(photo);
            sendPicture(img.getAbsolutePath());
        }

    }

    private File bitmapToPng(Bitmap bmp) {
        String fileName = getFilesDir().getAbsolutePath() + "/icon.png";
        File bitmapFile = new File(fileName);
        if (!bitmapFile.exists()) {
            try {
                bitmapFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream bitmapWtriter = null;
        try {
            bitmapWtriter = new FileOutputStream(bitmapFile);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, bitmapWtriter);
            bitmapWtriter.flush();
            bitmapWtriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmapFile;
    }

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 360);
        intent.putExtra("outputY", 360);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    private void sendPicture(final String filePath) {
        showProgress("正在上传文件...");
        // caculatePicture(new File(filePath));
        UploadPictureAPI.uploadPic(filePath, new AjaxCallBack<String>() {
            public void onLoading(long total, long current) {
                if (mListener != null) {
                    mListener.onUploading(total, current, mUploadTag);
                }
            }

            public void onSuccess(String s) {
                if (mListener != null) {
                    mListener.onSuccess(filePath, s, mUploadTag);
                }
                mUploadTag = -1;
                stopProgress();
            }

            public void onFailure(Throwable t, int errorNo, String strMsg) {
                if (mListener != null) {
                    mListener.onFailure(strMsg, mUploadTag);
                }
                stopProgress();
            }
        });
    }

    private void sendPicByUri(Uri selectedImage) {
        // String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
        String st8 = getResources().getString(R.string.cant_find_pictures);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex("_data");
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendPicture(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendPicture(file.getAbsolutePath());
        }

    }

    public interface OnFileUploadListener {
        public void onUploading(long total, long current, int tag);

        public void onSuccess(String fileLocalPath, String fileURL, int tag);

        public void onFailure(String msg, int tag);
    }

    private OnFileUploadListener mListener = null;

    public void setOnFileUploadListener(OnFileUploadListener l) {
        this.mListener = l;
    }

}
